package org.cnbi.web.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cnbi.utils.date.DateUtil;
import org.cnbi.utils.pojo.FileBean;
import org.cnbi.utils.pojo.SqlParamsBean;
import org.cnbi.web.controller.base.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
/**
 * Copyright © 2014中国经邦. All rights reserved.
 * @Author 龚佳新
 * @Time 2014年4月12日下午1:40:13
 */
@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController{
	private static final Log logger = LogFactory.getLog(UploadController.class);

	private static final String SWF = ".swf";
	/*@RequestMapping("/read")
	public ModelAndView read(HttpServletRequest request) {
		ModelAndView view  = new ModelAndView();
		String path = request.getParameter("path");
		try {
			path = new String(path.getBytes("ISO-8859-1"),"UTF-8");
			//String encode = java.net.URLDecoder.decode(path,"UTF-8");
			 // System.out.println("dd=="+dd);
			  //System.out.println("encode=="+encode);
			 String filePath = getRealPath("upload")+path;
			  filePath = filePath.replaceAll("\\\\", "/");
			  File file = new File(filePath);
				 String fileName = file.getName();
				//获取传过来的文件的扩展名
		         String extName=fileName.substring(fileName.lastIndexOf(".")+1);
		         if(extName.equalsIgnoreCase(SWF)){
		         }else{
				         System.out.println(filePath);
				         //调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法
				         OfficeDocumentConverter d = new OfficeDocumentConverter(filePath);
				         //调用conver方法开始转换，先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;
				     	 d.conver();
				     	 //调用getswfPath()方法，打印转换后的swf文件路径
				         System.out.println(d.getswfPath());
				     	 //生成swf相对路径，以便传递给flexpaper播放器
				         String swfpath = "upload"+d.getswfPath().substring(d.getswfPath().lastIndexOf("/"));
				         System.out.println(swfpath);
				         path = swfpath;
		         }
		         view.addObject("swfpath", path);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return view;
	}*/
	@RequestMapping("/upload") 
	public Object upload(SqlParamsBean sqlBean, HttpServletRequest request, HttpServletResponse response) {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		List list = new ArrayList();
		try {
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				// 得到要上传报告的路径
				String destPath = getRealPath("upload");
				while (iter.hasNext()) {
					MultipartFile file = multiRequest.getFile((String) iter.next());
					if (file != null && !file.equals("")) {// 如果文件不为空的情况下开始做上传文件操作
						String fileName = file.getOriginalFilename();// 得到要上传报告的名称
						// 因为上传的报告需要按年份、月份以及公司的文件夹分类，所以这里得到的路径是为了创建文件夹做准备的
						String path = destPath + sqlBean.getYear() + File.separator + sqlBean.getMonth() + File.separator;                        
						File localFile = new File(path);
						if (!localFile.exists()) {// 判断年份、月份以及公司编码的文件夹是否已经存在，如果没有就添加
							localFile.mkdirs();
						}
						// 创建上传的报告
						File localFiles = new File(path + fileName);
						file.transferTo(localFiles);
						list.add(path);

					}
				}
			}
		} 
		catch (IllegalStateException e) {
			logger.error("上传报告出错，，，");
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("上传报告出错，，，");
			e.printStackTrace();
		}
		return null;
	}

		@RequestMapping("/query")
		@ResponseBody
		public Object select(SqlParamsBean bean,HttpServletRequest request) {
			SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");// 格式化日期显示的格式
			String company = null, month = null, year = null;
			DecimalFormat df = new DecimalFormat(",000");

			month = bean.getMonth();
			year = bean.getYear();

			// 得到要遍历的文件夹的路径
			String filePath = request.getSession().getServletContext().getRealPath(File.separator) + "resource" + File.separator + "upload" + File.separator;
			filePath = filePath + year + File.separator + month + File.separator;

			List<FileBean> nameList = new ArrayList();
			Iterator it = getFiles(filePath).iterator();// 这个方法就是为了遍历路径下的所有的报告
			while (it.hasNext()) {
				FileBean fileBean = new FileBean();
				File iteFile = (File) it.next();
				// 设置文件实例的名称
				String name = iteFile.getName();
				name = "<a href=\"" + BaseController.getBasePath() + "resource" + "/" + "upload" + "/" + year + "/" + month + "/" + name + "\">" + name + "</a>";
				fileBean.setName(name);
				Long time = iteFile.lastModified();// 得到报告最后一次修改的时间
				Calendar cd = Calendar.getInstance();
				cd.setTimeInMillis(time);// 转换成日期类型
				fileBean.setModifyTime(timeFormat.format(cd.getTime()));// 设置文件实例的最后一次修改时间
				fileBean.setCreateTime(DateUtil.getCurDate(iteFile.getAbsolutePath()));// 设置文件实例的创建时间  上传

				if (iteFile.length() / 1024 >= 1000) {
					fileBean.setSize(df.format(iteFile.length() / 1024) + "KB");// 设置文件实例的大小
				} else {
					fileBean.setSize(iteFile.length() / 1024 + "KB");// 设置文件实例的大小
				}

				nameList.add(fileBean);
			}
			return nameList;
		}

	
		// 此方法就是为了遍历，文件夹下所有文件
		public List<File> getFiles(String filePath) {
			File root = new File(filePath);
			List<File> fileList = new ArrayList();
			File[] files = root.listFiles();// 将文件下所有的文件放到files数组里面

			if (null != files) {
				for (File file : files) {// 开始遍历数组
					if (file.isDirectory()) {// 如果表示的是一个目录则返回true，继续遍历目录下文件
						Iterator iter = getFiles(file.getAbsolutePath()).iterator();// 继续调用此方法，遍历调用

						while (iter.hasNext()) {
							File iteFile = (File) iter.next();
							fileList.add(iteFile);// 得到文件
						}
					} else {
						File newFile = new File(file.getAbsolutePath());
						fileList.add(newFile);// 得到文件
					}
				}
			} else {
				logger.info("此目录下文件为空啦！！！！");

			}
			return fileList;
		}

		// 修改报告名称的方法
		@RequestMapping("/edit")
		public Object edit(SqlParamsBean bean,HttpServletRequest request) {
			String nameR = request.getParameter("nameId");// 得到报告原来的名称
			String newName = request.getParameter("newName");// 得到修改的报告名称
			String month = null, year = null;

			month = bean.getMonth();
			year = bean.getYear();

			String filePath = request.getSession().getServletContext().getRealPath(File.separator) + "resource" + File.separator + "upload" + File.separator;
			filePath = filePath + year + File.separator + month + File.separator;
			Iterator it = getFiles(filePath).iterator();

			while (it.hasNext()) {
				File iteFile = (File) it.next();
				if (nameR.equals(iteFile.getName())) {// 遍历得到要修改的报告
					String testF = iteFile.getParent();
					File testN = new File(testF + File.separator + newName + nameR.substring(nameR.lastIndexOf("."), nameR.length()));

					if (iteFile.renameTo(testN)) {// 修改报告
						//System.out.println("修改成功喽！！！");
					} else {
						//System.out.println("修改失败喽！！！");
					}
					break;
				}
			}
			return null;
		}

		// 删除报告方法
		@RequestMapping("/remove")
		public Object remove(SqlParamsBean bean,HttpServletRequest request ) {
			String nameR = request.getParameter("removRName");
			String month = null, year = null;

			month = bean.getMonth();
			year = bean.getYear();

			String filePath = request.getSession().getServletContext().getRealPath(File.separator) + "resource" + File.separator + "upload" + File.separator;
			filePath = filePath + year + File.separator + month + File.separator;
			Iterator it = getFiles(filePath).iterator();

			while (it.hasNext()) {
				File iteFile = (File) it.next();
				if (nameR.equals(iteFile.getName()) && iteFile.exists()) {// 得到要删除的报告
					if (iteFile.delete()) {// 进行删除报告操作
						//System.out.println("删除文件成功啦！！！");
					} else {
						//System.out.println("删除文件失败啦！！！");
					}
					break;
				}
			}
			return null;
		}
		
		public static void main(String[] args) {
			String fileName = "dddd.txts";
			 String extName=fileName.substring(fileName.lastIndexOf(".")+1);
			 System.out.println("extName=="+extName);
		}
}
